package com.faintlight.service.impl;

import com.faintlight.dto.ChainDTO;
import com.faintlight.exception.WarmException;
import com.faintlight.model.*;
import com.faintlight.repository.ChainRepository;
import com.faintlight.service.CapsuleService;
import com.faintlight.service.ChainService;
import com.faintlight.service.UserService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

import static com.faintlight.model.Capsule.Status.UNLOCKED;

@Service
@RequiredArgsConstructor
public class ChainServiceImpl implements ChainService {

    private static final Logger logger = LoggerFactory.getLogger(ChainServiceImpl.class);
    private static final int MAX_CHAIN_LENGTH = 5;

    private final ChainRepository chainRepository;
    private final UserService userService;
    private final CapsuleService capsuleService;

    @Override
    @Transactional
    public ChainDTO startChain(Long capsuleId, Long userId) {
        Capsule capsule = capsuleService.getCapsuleById(capsuleId);
        if (capsule == null) throw new WarmException("未找到指定胶囊");
        if (capsule.getStatus() != UNLOCKED) throw new WarmException("只有已解锁的胶囊才能启动传递");
        if (chainRepository.existsBySourceCapsule_Id(capsuleId)) throw new WarmException("该胶囊已有传递链");
        KindnessChain chain = new KindnessChain();
        chain.setSourceCapsule(capsule);
        KindnessChain saved = chainRepository.save(chain);
        return ChainDTO.fromEntity(saved);
    }

    @Override
    @Transactional
    public ChainDTO addNodeToChain(Long chainId, Long userId, String message) {
        KindnessChain chain = chainRepository.findById(chainId)
                .orElseThrow(() -> new WarmException("传递链不存在"));
        String sanitizedMessage = message.replaceAll("(累|疲惫|难过|烦|苦|痛)", "疲惫的云");
        ChainNode node = new ChainNode();
        node.setChain(chain);
        node.setParticipant(userService.getUserById(userId));
        node.setMessage(sanitizedMessage);
        node.setSequence(chain.getNodes().size() + 1);
        chain.getNodes().add(node);
        if (chain.getNodes().size() >= MAX_CHAIN_LENGTH) {
            chain.setCompleted(true);
            Capsule capsule = chain.getSourceCapsule();
            capsule.setTemperature(40 + chain.getNodes().size() * 3);
        }
        chainRepository.save(chain);
        return ChainDTO.fromEntity(chain);
    }

    @Override
    public ChainDTO getChainById(Long chainId) {
        return chainRepository.findById(chainId)
                .map(ChainDTO::fromEntity)
                .orElseThrow(() -> new WarmException("传递链不存在"));
    }

    @Override
    public List<ChainDTO> getAllChains() {
        return chainRepository.findAll().stream().map(ChainDTO::fromEntity).collect(Collectors.toList());
    }
    @Override
    public List<ChainDTO> getChainsByParticipant(Long userId) {
        List<KindnessChain> chains = chainRepository.findByParticipantIdOrderByCreatedAtDesc(userId);
        return chains.stream().map(ChainDTO::fromEntity).collect(Collectors.toList());
    }


    @Override
    public Long getUserChainCount(Long userId) {

        return chainRepository.countByNodesParticipantId(userId);

    }
}